package com.citic.topview.system.persistence;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;

import com.citic.topview.common.persistence.CrudDao;
import com.citic.topview.common.persistence.DataEntity;
import com.citic.topview.common.util.IdGen;
import com.citic.topview.system.util.ShiroUtils;

public abstract class CrudService<D extends CrudDao<T>, T extends DataEntity<T>> {

	@Autowired
	protected D dao;
	
	public T get(Long id) {
		return dao.get(id);
	}
	
	public int save(T entity) {
		if(null == entity.getId()) {
			Date date = new Date();
			entity.setId(IdGen.snowFlakeId());
			entity.setCreateTime(date);
			entity.setCreateBy(ShiroUtils.getPrincipal() != null ? ShiroUtils.getPrincipal().getId() : null);
			entity.setDelFlag("0");
			entity.setModifiedTime(date);
			entity.setModifiedBy(ShiroUtils.getPrincipal() != null ? ShiroUtils.getPrincipal().getId() : null);
		}
		
		return dao.save(entity);
	}
	
	public int update(T entity) {
		entity.setModifiedTime(new Date());
		entity.setModifiedBy(ShiroUtils.getPrincipal() != null ? ShiroUtils.getPrincipal().getId() : null);
		return dao.update(entity);
	}
	
	public int deleteByDelFlag(Long id) {
		return dao.deleteByDelFlag(id);
	}
	
	public int remove(Long id) {
		return dao.remove(id);
	}
	
	public int batchRemove(Long[] ids) {
		return dao.batchRemove(ids);
	}
}
